import { ElDialog, ElInput, ElButton } from "element-plus";
import { defineComponent, createVNode, render, reactive } from "vue";

const DialogComponent = defineComponent({
    props: {
        option: {type: Object}
    },
    setup(props, ctx){
        const state = reactive({
            option: props.option,
            isShow: false
        })
        ctx.expose({ // 让外界可以调用组件内部的方法
            showDialog(option){
                state.option = option
                state.isShow = true
            }
        })

        const onCancle = () => {
            state.isShow = false
        }

        const onConfirm = () => {
            state.isShow = false
            state.option.onConfirm && state.option.onConfirm(state.option.content)
        }

        return () => {
            return <ElDialog v-model={state.isShow}>{{
                default: () => <ElInput
                    type="textarea"
                    v-model={state.option.content}
                />,
                footer: () => state.option.footer && <div>
                    <ElButton onClick={onCancle}>取消</ElButton>
                    <ElButton onClick={onConfirm} type="primary">确定</ElButton>
                </div>
            }}</ElDialog>
        }
    }
})


let vm

export function $dialog(option) {
    if(!vm){
        let el = document.createElement('div')
        vm = createVNode(DialogComponent, {option}) // 将组建渲染成虚拟节点
        document.body.appendChild((render(vm, el), el)) // 渲染成真实节点 扔到dom中去
    }
    let { showDialog } = vm.component.exposed
    showDialog(option)
}
